package com.engine.shunsheng.util;

import com.engine.kq.biz.KQLeaveRulesComInfo;
import com.engine.kq.biz.KQUsageHistoryBiz;
import com.engine.kq.entity.KQUsageHistoryEntity;
import org.apache.commons.lang3.StringUtils;
import weaver.conn.RecordSet;
import weaver.general.BaseBean;
import weaver.general.Util;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.Period;
import java.time.format.DateTimeFormatter;
import java.time.temporal.TemporalAdjusters;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

/**
 * @version 1.0
 * @Title ecology-9
 * @Company 泛微软件
 * @CreateDate 2024/8/23
 * @Description 处理外籍年假
 * @Author AdminZm
 */
public class HandleForeignAnnualLeaveUtil {

    BaseBean baseBean = new BaseBean();

    public void handleForeignAnnualLeave() {
        baseBean.writeLog("handleForeignAnnualLeave start.");
        RecordSet rs = new RecordSet();
        RecordSet rs1 = new RecordSet();
        RecordSet rs2 = new RecordSet();
        try {
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
            LocalDate currentDate = LocalDate.now(); // 获取当前日期
            int year = currentDate.getYear();        // 获取年份
            int month = currentDate.getMonthValue();  // 获取月份
            int day = currentDate.getDayOfMonth();    // 获取日期

            int qnYear = currentDate.minusYears(1).getYear();    // 获取上一年年份

            baseBean.writeLog("year、month、day：" + year + "、" + month + "、" + day);

            // 判断今天是否本月最后一天
            LocalDate nextDate = currentDate.plusDays(1);
            int monthValue = nextDate.getMonthValue();
            boolean isLastDay = monthValue - month != 0;
            baseBean.writeLog("isLastDay:" + isLastDay);
            // 获取本月最后一天
            LocalDate lastDayOfMonth = currentDate.with(TemporalAdjusters.lastDayOfMonth());
            int dayLastOfMonth = lastDayOfMonth.getDayOfMonth();

            String wjnjid = baseBean.getPropValue("ss_prop_zm", "foreign_annual_leave_rule_id");

            String insertSql = "insert into kq_BalanceOfLeave(baseAmount,extraAmount,usedAmount,baseAmount2,extraAmount2,usedAmount2,leaveRulesId,resourceId,belongYear,belongMonth) values(?,?,?,?,?,?,?,?,?,?) ";

            List<KQUsageHistoryEntity> usageHistoryEntities = new ArrayList<KQUsageHistoryEntity>();
            KQUsageHistoryEntity usageHistoryEntity = null;
            Calendar today = Calendar.getInstance();
            String currentDateStr = Util.add0(today.get(Calendar.YEAR), 4) + "-"
                    + Util.add0(today.get(Calendar.MONTH) + 1, 2) + "-"
                    + Util.add0(today.get(Calendar.DAY_OF_MONTH), 2);
            String currentTime = Util.add0(today.get(Calendar.HOUR_OF_DAY), 2) + ":" +
                    Util.add0(today.get(Calendar.MINUTE), 2) + ":" +
                    Util.add0(today.get(Calendar.SECOND), 2);

            //假期类型缓存类
            KQLeaveRulesComInfo rulesComInfo = new KQLeaveRulesComInfo();
            //最小请假单位：1-按天请假、2-按半天请假、3-按小时请假、4-按整天请假
            String minimumUnit = rulesComInfo.getMinimumUnit(wjnjid);

            String sql = " select a.id,a.lastname,a.companystartdate, b.field24 from HrmResource a, cus_fielddata b where a.id = b.id " +
                    "and a.status in (0,1,2,3) and a.companystartdate is not null and b.scope = 'HrmCustomFieldByInfoType' " +
                    "and b.scopeid = 3 and a.id not in (select resourceid from kq_BalanceOfLeave where belongYear = ? and leaveRulesId=? and belongMonth = ?)";
            rs.executeQuery(sql, year, wjnjid, month);

            while (rs.next()) {
                String id = rs.getString("id");
                baseBean.writeLog("handleForeignAnnualLeave id:" + id);
                String companystartdate = rs.getString("companystartdate");
                String zzrq = rs.getString("field24");

                // 转正日期为空不考虑
                if (StringUtils.isEmpty(zzrq)) {
                    continue;
                }
                // 未到转正日期不考虑
                LocalDate localDateZz = LocalDate.parse(zzrq, formatter);
                if (currentDate.compareTo(localDateZz) < 0) {
                    continue;
                }
                LocalDate localDate = LocalDate.parse(companystartdate, formatter);
                int dayTemp = localDate.getDayOfMonth();
                int yearTemp = localDate.getYear();        // 获取年份
                int monthTemp = localDate.getMonthValue();  // 获取月份

                baseBean.writeLog("yearTemp、monthTemp、dayTemp：" + yearTemp + "、" + monthTemp + "、" + dayTemp);
                // 日期相同直接发放
                // 日期不同，则判断是否本月没有该日期，有的话跳过，没有则本月最后一日发放
                if ((dayTemp == day) || (dayTemp > dayLastOfMonth && isLastDay)) {
                    // 考虑转正日期逻辑 如果今日和入职日期之间没有数据，则补充数据
                    String sqlTempA = "select count(*) as cnt from kq_BalanceOfLeave where  leaveRulesId=? and resourceid = ? and ((belongYear = ? and belongMonth < ?) or " +
                            " (belongYear = ? and belongMonth > ?) ";
                    for (int i = yearTemp + 1; i < year; i++) {
                        sqlTempA = sqlTempA + " or belongYear = '" + i + "' ";
                    }
                    sqlTempA = sqlTempA + ")";
                    baseBean.writeLog("sqlTemp is:" + sqlTempA);
                    rs1.executeQuery(sqlTempA, wjnjid, id, year, month, yearTemp, monthTemp);
                    if (rs1.next()) {
                        int cnt = rs1.getInt("cnt");
                        if (cnt <= 0) {
                            if (yearTemp == year) {
                                for (int y = monthTemp + 1; y < month; y++) {
                                    // 将结余存为额外
                                    rs2.executeUpdate(insertSql, "168", "0", "0", "0", "0", "0", wjnjid, id, year, y);
                                    usageHistoryEntity = new KQUsageHistoryEntity();
                                    usageHistoryEntity.setLeaveRulesId("" + wjnjid);
                                    usageHistoryEntity.setRelatedId("" + id);
                                    usageHistoryEntity.setOperator("1");
                                    usageHistoryEntity.setOperateDate(currentDateStr);
                                    usageHistoryEntity.setOperateTime(currentTime);
                                    usageHistoryEntity.setOperateType("6");
                                    usageHistoryEntity.setBelongYear("" + year);
                                    usageHistoryEntity.setNewBaseAmount("14");
                                    usageHistoryEntity.setNewExtraAmount("0");
                                    usageHistoryEntity.setNewUsedAmount("0");
                                    usageHistoryEntity.setNewBaseAmount2("0");
                                    usageHistoryEntity.setNewExtraAmount2("0");
                                    usageHistoryEntity.setNewUsedAmount2("0");
                                    usageHistoryEntity.setOldMinimumUnit(minimumUnit);
                                    usageHistoryEntity.setNewMinimumUnit(minimumUnit);
                                    usageHistoryEntity.setInsertOrUpdate("insert");
                                    usageHistoryEntities.add(usageHistoryEntity);
                                }
                            } else {
                                for (int n = yearTemp; n <= year; n++) {
                                    if (n == yearTemp) {
                                        for (int y = monthTemp + 1; y <= 12; y++) {
                                            rs2.executeUpdate(insertSql, "168", "0", "0", "0", "0", "0", wjnjid, id, n, y);
                                            usageHistoryEntity = new KQUsageHistoryEntity();
                                            usageHistoryEntity.setLeaveRulesId("" + wjnjid);
                                            usageHistoryEntity.setRelatedId("" + id);
                                            usageHistoryEntity.setOperator("1");
                                            usageHistoryEntity.setOperateDate(currentDateStr);
                                            usageHistoryEntity.setOperateTime(currentTime);
                                            usageHistoryEntity.setOperateType("6");
                                            usageHistoryEntity.setBelongYear("" + n);
                                            usageHistoryEntity.setNewBaseAmount("14");
                                            usageHistoryEntity.setNewExtraAmount("0");
                                            usageHistoryEntity.setNewUsedAmount("0");
                                            usageHistoryEntity.setNewBaseAmount2("0");
                                            usageHistoryEntity.setNewExtraAmount2("0");
                                            usageHistoryEntity.setNewUsedAmount2("0");
                                            usageHistoryEntity.setOldMinimumUnit(minimumUnit);
                                            usageHistoryEntity.setNewMinimumUnit(minimumUnit);
                                            usageHistoryEntity.setInsertOrUpdate("insert");
                                            usageHistoryEntities.add(usageHistoryEntity);
                                        }
                                    }
                                    if (n > yearTemp && n < year) {
                                        for (int y = 1; y <= 12; y++) {
                                            rs2.executeUpdate(insertSql, "168", "0", "0", "0", "0", "0", wjnjid, id, n, y);
                                            usageHistoryEntity = new KQUsageHistoryEntity();
                                            usageHistoryEntity.setLeaveRulesId("" + wjnjid);
                                            usageHistoryEntity.setRelatedId("" + id);
                                            usageHistoryEntity.setOperator("1");
                                            usageHistoryEntity.setOperateDate(currentDateStr);
                                            usageHistoryEntity.setOperateTime(currentTime);
                                            usageHistoryEntity.setOperateType("6");
                                            usageHistoryEntity.setBelongYear("" + n);
                                            usageHistoryEntity.setNewBaseAmount("14");
                                            usageHistoryEntity.setNewExtraAmount("0");
                                            usageHistoryEntity.setNewUsedAmount("0");
                                            usageHistoryEntity.setNewBaseAmount2("0");
                                            usageHistoryEntity.setNewExtraAmount2("0");
                                            usageHistoryEntity.setNewUsedAmount2("0");
                                            usageHistoryEntity.setOldMinimumUnit(minimumUnit);
                                            usageHistoryEntity.setNewMinimumUnit(minimumUnit);
                                            usageHistoryEntity.setInsertOrUpdate("insert");
                                            usageHistoryEntities.add(usageHistoryEntity);
                                        }
                                    }
                                    if (n == year) {
                                        for (int y = 1; y < month; y++) {
                                            rs2.executeUpdate(insertSql, "168", "0", "0", "0", "0", "0", wjnjid, id, n, y);
                                            usageHistoryEntity = new KQUsageHistoryEntity();
                                            usageHistoryEntity.setLeaveRulesId("" + wjnjid);
                                            usageHistoryEntity.setRelatedId("" + id);
                                            usageHistoryEntity.setOperator("1");
                                            usageHistoryEntity.setOperateDate(currentDateStr);
                                            usageHistoryEntity.setOperateTime(currentTime);
                                            usageHistoryEntity.setOperateType("6");
                                            usageHistoryEntity.setBelongYear("" + n);
                                            usageHistoryEntity.setNewBaseAmount("14");
                                            usageHistoryEntity.setNewExtraAmount("0");
                                            usageHistoryEntity.setNewUsedAmount("0");
                                            usageHistoryEntity.setNewBaseAmount2("0");
                                            usageHistoryEntity.setNewExtraAmount2("0");
                                            usageHistoryEntity.setNewUsedAmount2("0");
                                            usageHistoryEntity.setOldMinimumUnit(minimumUnit);
                                            usageHistoryEntity.setNewMinimumUnit(minimumUnit);
                                            usageHistoryEntity.setInsertOrUpdate("insert");
                                            usageHistoryEntities.add(usageHistoryEntity);
                                        }
                                    }
                                }
                            }
                        }
                    }
                    // 判断是否为一周期
                    baseBean.writeLog("zq:" + (yearTemp != year && (month - monthTemp) == 0));
                    if (yearTemp != year && (month - monthTemp) == 0) {
                        String sqlTemp = "select count(*) * 14 as baseAmount, sum(usedAmount) as allUsedAmount, sum(extraAmount) as allExtraAmount from kq_BalanceOfLeave " +
                                " where leaveRulesId = ? and resourceid = ? and (status is null or status != 1)";
                        rs1.executeQuery(sqlTemp, wjnjid, id);
                        if (rs1.next()) {
                            String allBaseAmount = rs1.getString("baseAmount");
                            String allUsedAmount = rs1.getString("allUsedAmount");
                            String allExtraAmount = rs1.getString("allExtraAmount");
                            double baseAmount = Util.getDoubleValue(allBaseAmount, 0.00);
                            double extraAmount = Util.getDoubleValue(allExtraAmount, 0.00);
                            double usedAmount = Util.getDoubleValue(allUsedAmount, 0.00);
                            String restAmount = "0";
                            if (baseAmount + extraAmount - usedAmount > 58) {
                                restAmount = "58";
                            } else {
                                restAmount = String.format("%.2f", baseAmount + extraAmount - usedAmount);
                            }

                            // 先将之前的状态改为失效
                            rs2.executeUpdate("UPDATE kq_BalanceOfLeave SET status = 1 WHERE leaveRulesId = ? and resourceid = ?",
                                    wjnjid, id);
                            // 将结余存为额外
                            rs2.executeUpdate(insertSql, "168", restAmount, "0", "0", "0", "0", wjnjid, id, year, month);
                            usageHistoryEntity = new KQUsageHistoryEntity();
                            usageHistoryEntity.setLeaveRulesId("" + wjnjid);
                            usageHistoryEntity.setRelatedId("" + id);
                            usageHistoryEntity.setOperator("1");
                            usageHistoryEntity.setOperateDate(currentDateStr);
                            usageHistoryEntity.setOperateTime(currentTime);
                            usageHistoryEntity.setOperateType("6");
                            usageHistoryEntity.setBelongYear("" + year);
                            usageHistoryEntity.setNewBaseAmount("14");
                            usageHistoryEntity.setNewExtraAmount(restAmount);
                            usageHistoryEntity.setNewUsedAmount("0");
                            usageHistoryEntity.setNewBaseAmount2("0");
                            usageHistoryEntity.setNewExtraAmount2("0");
                            usageHistoryEntity.setNewUsedAmount2("0");
                            usageHistoryEntity.setOldMinimumUnit(minimumUnit);
                            usageHistoryEntity.setNewMinimumUnit(minimumUnit);
                            usageHistoryEntity.setInsertOrUpdate("insert");
                            usageHistoryEntities.add(usageHistoryEntity);
                        }
                    } else {
                        rs2.executeUpdate(insertSql, "168", "0", "0", "0", "0", "0", wjnjid, id, year, month);
                        usageHistoryEntity = new KQUsageHistoryEntity();
                        usageHistoryEntity.setLeaveRulesId("" + wjnjid);
                        usageHistoryEntity.setRelatedId("" + id);
                        usageHistoryEntity.setOperator("1");
                        usageHistoryEntity.setOperateDate(currentDateStr);
                        usageHistoryEntity.setOperateTime(currentTime);
                        usageHistoryEntity.setOperateType("6");
                        usageHistoryEntity.setBelongYear("" + year);
                        usageHistoryEntity.setNewBaseAmount("14");
                        usageHistoryEntity.setNewExtraAmount("0");
                        usageHistoryEntity.setNewUsedAmount("0");
                        usageHistoryEntity.setNewBaseAmount2("0");
                        usageHistoryEntity.setNewExtraAmount2("0");
                        usageHistoryEntity.setNewUsedAmount2("0");
                        usageHistoryEntity.setOldMinimumUnit(minimumUnit);
                        usageHistoryEntity.setNewMinimumUnit(minimumUnit);
                        usageHistoryEntity.setInsertOrUpdate("insert");
                        usageHistoryEntities.add(usageHistoryEntity);
                    }
                } else {
                    // 考虑历史数据逻辑
                    String dataId = null;
                    rs1.executeQuery("SELECT id FROM kq_BalanceOfLeave WHERE leaveRulesId = ? AND resourceid = ? " +
                            "AND belongYear = ? AND belongMonth = ?", wjnjid, id, qnYear, monthTemp);
                    if (rs1.next()) {
                        dataId = rs1.getString("id");
                    }
                    if (StringUtils.isNotEmpty(dataId) && new BigDecimal(dataId).compareTo(BigDecimal.ZERO) > 0) {
                        String sqlTemp = "select count(*) * 14 as baseAmount, sum(usedAmount) as allUsedAmount, sum(extraAmount) as allExtraAmount " +
                                " from kq_BalanceOfLeave where  leaveRulesId = ? and resourceid = ? and ((belongYear = ? and belongMonth < ?) or " +
                                " (belongYear < ?)) and (status is null or status != 1)";
                        rs1.executeQuery(sqlTemp, wjnjid, id, qnYear, monthTemp, qnYear);
                        if (rs1.next()) {
                            String allBaseAmount = rs1.getString("baseAmount");
                            String allUsedAmount = rs1.getString("allUsedAmount");
                            String allExtraAmount = rs1.getString("allExtraAmount");
                            double baseAmount = Util.getDoubleValue(allBaseAmount, 0.00);
                            double extraAmount = Util.getDoubleValue(allExtraAmount, 0.00);
                            double usedAmount = Util.getDoubleValue(allUsedAmount, 0.00);
                            String restAmount = "0";
                            if (baseAmount + extraAmount - usedAmount > 58) {
                                restAmount = "58";
                            } else {
                                restAmount = String.format("%.2f", baseAmount + extraAmount - usedAmount);
                            }

                            // 先将之前的状态改为失效
                            rs2.executeUpdate("UPDATE kq_BalanceOfLeave SET status = 1 WHERE leaveRulesId = ? and resourceid = ? " +
                                            " and ((belongYear = ? and belongMonth < ?) or (belongYear < ?)) and (status is null or status != 1)",
                                    wjnjid, id, qnYear, monthTemp, qnYear);
                            // 将结余存为额外
                            rs2.executeUpdate("update kq_BalanceOfLeave set extraAmount = ? where id = ?", restAmount, dataId);
//                            usageHistoryEntity = new KQUsageHistoryEntity();
//                            usageHistoryEntity.setLeaveRulesId("" + wjnjid);
//                            usageHistoryEntity.setRelatedId("" + id);
//                            usageHistoryEntity.setOperator("1");
//                            usageHistoryEntity.setOperateDate(currentDateStr);
//                            usageHistoryEntity.setOperateTime(currentTime);
//                            usageHistoryEntity.setOperateType("6");
//                            usageHistoryEntity.setBelongYear("" + year);
//                            usageHistoryEntity.setNewBaseAmount("14");
//                            usageHistoryEntity.setNewExtraAmount(restAmount);
//                            usageHistoryEntity.setNewUsedAmount("0");
//                            usageHistoryEntity.setNewBaseAmount2("0");
//                            usageHistoryEntity.setNewExtraAmount2("0");
//                            usageHistoryEntity.setNewUsedAmount2("0");
//                            usageHistoryEntity.setOldMinimumUnit(minimumUnit);
//                            usageHistoryEntity.setNewMinimumUnit(minimumUnit);
//                            usageHistoryEntity.setInsertOrUpdate("update");
//                            usageHistoryEntities.add(usageHistoryEntity);
                        }
                    }
                }
            }

            /*记录员工假期余额变更记录 start*/
            KQUsageHistoryBiz kqUsageHistoryBiz = new KQUsageHistoryBiz();
            boolean isSuccess = false;
            if (usageHistoryEntities.size() > 0) {
                isSuccess = kqUsageHistoryBiz.save(usageHistoryEntities);
            }
            baseBean.writeLog("handleForeignAnnualLeave isSuccess:" + isSuccess);
            /*记录员工假期余额变更记录 end*/
        } catch (Exception e) {
            baseBean.writeLog("handleForeignAnnualLeave error:" + e.getMessage());
        }
        baseBean.writeLog("handleForeignAnnualLeave end.");
    }
}
